package com.huitone.smspfm.interfacz.tasks;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.interfacz.core.AppStaticConfigs;
import com.huitone.smspfm.interfacz.core.filewriter.CuttingFileConfig;
import com.huitone.smspfm.interfacz.core.filewriter.FileRoute;
import com.huitone.smspfm.interfacz.core.filewriter.FileWriterClient;
import com.huitone.smspfm.interfacz.core.filewriter.RedUserReportWriter;
import com.huitone.smspfm.interfacz.core.filewriter.WriterInterface;
import com.huitone.smspfm.interfacz.logger.ExtLogger;


/**
 * 读写文件管理类
 * @author Administrator
 *
 */
public class FileWriterTask extends Thread{
	
	private static final ExtLogger logger = ExtLogger.create(FileWriterTask.class);
	
	private int corePoolSize = 10;
	
	private int maximumPoolSize = 20;
	
	private long keepAliveTime = 1L;
	
	private boolean keepGoing = true;
	
//	private boolean toSleep = false;
	
//	private static final String SMS_SEND = "SEND";
//	private static final String SMS_REPORT = "REPORT";
	
//	private static final String SMS_RED_USER_REPORT = "RED_USER_REPORT";
	
	//文件写入分类集合
	public static Map<String,WriterInterface>  map = new HashMap<String, WriterInterface>();
	
	//要写入的文件队列，异步写入
	public static ConcurrentLinkedQueue<FileRoute> queue = new ConcurrentLinkedQueue<FileRoute>();
	
	//线程 池进行写入操作
	private ExecutorService  fileWriterPool = new ThreadPoolExecutor(corePoolSize, 
			maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<>(maximumPoolSize * 2), new RejectedExecutionHandler() {
		
		@Override
		public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
			boolean flag = false;
			while(!executor.isShutdown() && !flag) {
				flag = executor.getQueue().offer(r);
				if (!flag) {
					try {
						TimeUnit.MILLISECONDS.sleep(10);
					} catch (InterruptedException e) {}
				}
			}
		}
	});
	
	private void init(){
//		if(! map.containsKey(SMS_SEND)){
//			
//		}
		
		
//		if(! map.containsKey(SMS_REPORT)){
//			//TODO 文件路径
//			FileWriterClient client = FileWriterClient.getFileWriterClient(AppStaticConfigs.smsOldFilePath, AppStaticConfigs.smsOldFileName, 
//					new CuttingFileConfig("report","txt"));
//			
//			client.setWrapLeft("<data>");
//			client.setWrapRight("</data>");
//			if(client != null)	{
//				map.put(SMS_REPORT,client );
//			}
//		}
	}

	@Override
	public void run() {
		init();
		while(keepGoing && this.isAlive()){
			fileWriterPool.execute(new Runnable() {
				
				@Override
				public void run() {
					while (!queue.isEmpty()){
						try {
							FileRoute fileRoute = queue.poll();
							if(fileRoute == null){
								continue;
							}
							String key = fileRoute.getKey();
							String msg = fileRoute.getValue();
							
							if(map.get(key) != null && map.get(key).isWriter()){
								map.get(key).write(msg);
							} else {
								createFileWrite(key);
								map.get(key).write(msg);
							}
							
						} catch (IOException e) {
							e.printStackTrace();
						}
					} 
					
				}
			});

			try {
				Thread.sleep(1000L);
			} catch (InterruptedException e) {
			}

		}
		logger.info("文件处理线程已经退出");
	}
	
	
	protected void createFileWrite(String key) {
		if(StringUtils.equals(FileRoute.KEY_SMS_OLD_SEND, key)){
			CuttingFileConfig config = new CuttingFileConfig("send",".txt"); 
			FileWriterClient client = FileWriterClient.getFileWriterClient(AppStaticConfigs.smsOldFilePath, AppStaticConfigs.smsOldFileName,config);
			
			
			if(client != null)	{
				client.setWrapLeft("<data>");
				client.setWrapRight("</data>");
				client.setIntvToCut(1*60*1000L);
				client.setLineToCut(1000);
				map.put(key,client );
				client.enableWatchDog();
			}
		} else if(StringUtils.startsWith(key, FileRoute.KEY_RED_USER_REPORT)){
			String doublePath = StringUtils.substring(key, FileRoute.KEY_RED_USER_REPORT.length());
			if(StringUtils.isEmpty(doublePath)){
				doublePath = FileRoute.KEY_RED_USER_REPORT;
			}
			CuttingFileConfig config = new CuttingFileConfig("resp",".xml"); 
//			config.set
			RedUserReportWriter client = RedUserReportWriter.getFileWriterClient(AppStaticConfigs.redUserFilePath+File.separator+doublePath, AppStaticConfigs.redUserFileName, config);
			
			if(client != null){
				client.setWrapLeft("<data>");
				client.setWrapRight("</data>");
				client.setIntvToCut(1*60*60*1000L);
				client.setLineToCut(1000);
				map.put(key, client);
				client.enableWatchDog();
			}
		}
		
		
	}

	public boolean isKeepGoing() {
		return keepGoing;
	}

	public void setKeepGoing(boolean keepGoing) {
		this.keepGoing = keepGoing;
	}

	@Override
	public void destroy() {
		if(map.size() > 0){
			for(String key :map.keySet()){
				map.get(key).destroy();
				map.remove(key);
			}
		}
		this.setKeepGoing(false);
		this.interrupt();
		if (this.fileWriterPool != null) {
			this.fileWriterPool.shutdown();
			this.fileWriterPool = null;
		}
		
	}
	
}
